package cn.kgc.dm.service.impl;

import cn.kgc.dm.common.MD5;
import cn.kgc.dm.common.RedisUtils;
import cn.kgc.dm.common.TokenValidationFailedException;
import cn.kgc.dm.pojo.DmUser;
import cn.kgc.dm.service.TokenService;
import cn.kgc.dm.vo.DmUserVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author: 12138
 * @CreateTime: 2019/05/14
 */
@Service
public class TokenServiceImpl implements TokenService {
	
	@Autowired
	private RedisUtils redisUtils;
	
	@Override
	public String generateUuid(String phone) {
		StringBuffer uuid = new StringBuffer();
		uuid.append("uuid:");
		uuid.append(MD5.getMd5(phone, 32));
		return uuid.toString();
	}
	
	@Override
	public void saveUuid(String uuid, String token) {
		redisUtils.set(uuid, 60 * 60 * 2, token);
	}
	
	@Override
	public String generateToken(String agent, DmUserVO dmUserVO) {
		StringBuffer token = new StringBuffer();
		token.append("token:");
		token.append("PC-");
		token.append(MD5.getMd5(dmUserVO.getPhone(), 32) + "-");
		token.append(dmUserVO.getUserId() + "-");
		token.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "-");
		token.append(MD5.getMd5(agent, 6));
		return token.toString();
	}
	
	@Override
	public void saveToken(String token, DmUserVO dmUserVO) {
		redisUtils.set(token, 60 * 60 * 2, JSON.toJSONString(dmUserVO));
	}
	
	@Override
	public DmUserVO load(String token) {
		return JSON.parseObject(redisUtils.get(token).toString(), DmUserVO.class);
	}
	
	@Override
	public void del(String token) {
		redisUtils.delete(token);
	}
	
	@Override
	public String replaceToken(String agent, String token) throws TokenValidationFailedException, ParseException {
		if(!redisUtils.exist(token)){
			throw new TokenValidationFailedException("token无效或过期");
		}
		Date startDate = null;
		// 获取token生成时间
		String[] split = token.split("-");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		try {
			startDate = simpleDateFormat.parse(split[3]);
			long l = Calendar.getInstance().getTimeInMillis() - startDate.getTime();
			if(l < 60 * 60 * 1000){
				throw new TokenValidationFailedException("token未到置换时间");
			}
			if(redisUtils.getExpire(token) < 0){
				throw new TokenValidationFailedException("token过期请重新登录");
			}
			DmUserVO dmUserVO = load(token);
			String newToken = generateToken(agent, dmUserVO);
			redisUtils.set(token, 60 * 2, JSON.toJSONString(dmUserVO));
			saveToken(newToken, dmUserVO);
			return newToken;
		} catch (ParseException e) {
			e.printStackTrace();
			throw new ParseException("token格式错误", e.getErrorOffset());
		}
	}
}


